package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.Employee;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R login(@RequestBody Employee employee) {
        R r = employeeService.login(employee);
        if (r.getCode() == 1) {
            HttpSession session = request.getSession();
            session.setAttribute("employee", ((Employee) r.getData()).getId());
        }
        return r;
    }

    @PostMapping("/logout")
    public R logout() {
        HttpSession session = request.getSession();
        session.invalidate();
        return R.success("退出成功");
    }

    @PostMapping
    public R add(@RequestBody Employee employee) {
        String passwordMd5 = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(passwordMd5);
//        employee.setCreateTime(new Date());
//        employee.setUpdateTime(new Date());
//        HttpSession session = request.getSession();
//        long employee2 = (long) session.getAttribute("employee");
//        employee.setUpdateUser(employee2);
//        employee.setCreateUser(employee2);
        R r = employeeService.save(employee);
        return r;
    }
    @GetMapping("/page")
    public R page(int page, int pageSize, String name) {
        R r = employeeService.page(page, pageSize, name);
        ArrayList<Object> list = new ArrayList<>();
        return r;
    }
    @PutMapping
    public R update(@RequestBody Employee employee) {
//        HttpSession session = request.getSession();
//        Long employee1 = (Long) session.getAttribute("employee");
//        employee.setCreateUser(employee1);
//        employee.setUpdateUser(employee1);
//        employee.setUpdateTime(new Date());
        R r = employeeService.update(employee);
        return r;
    }
    @GetMapping("/{id}")
    public R findById(@PathVariable Long id) {
        R r = employeeService.findById(id);
        return r;
    }
}
